/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月8日 下午3:44:54
 */

package datang.dtdb.executor;

import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.ExecutionException;

import datang.dtdb.exceptions.ExecutorException;
import datang.dtdb.executor.statement.StatementHandler;
import datang.dtdb.mapping.BoundSql;
import datang.dtdb.mapping.MappedStatement;
import datang.dtdb.session.Configuration;
import datang.dtdb.session.ResultHandler;
import datang.dtdb.transaction.Transaction;

/**
 * 执行器子类
 */
public class SimpleExecutor extends BaseExecutor {

	public SimpleExecutor(Configuration configuration, Transaction transaction) {
		super(configuration, transaction);
	}

	/**
	 * 查询
	 */
	@Override
	protected <E> List<E> doQuery(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds,
			ResultHandler resultHandler, BoundSql boundSql) {
		Statement statement = null;
		try {
			StatementHandler statementHandler = configuration.newStatementHandler(this, mappedStatement, parameter,
					rowBounds, resultHandler, boundSql);
			statement = prepareStatement(statementHandler);
			return statementHandler.query(statement, resultHandler);
		} finally {
			closeStatement(statement);
		}

	}

	/**
	 * insert update delete
	 */
	@Override
	protected int doUpdate(MappedStatement mappedStatement, Object parameter) {
		Statement statement = null;
		try {
			StatementHandler statementHandler = configuration.newStatementHandler(this, mappedStatement, parameter,
					null, null, mappedStatement.getBoundSql(parameter));
			statement = prepareStatement(statementHandler);
			return statementHandler.update(statement);
		} finally {
			closeStatement(statement);
		}

	}

	/**
	 * 从statementHandler获取具体类型的statement
	 */
	private Statement prepareStatement(StatementHandler statementHandler) {
		Connection connection = getConnection();
		Statement statement = statementHandler.prepare(connection);
		// 对于preparedStatement类型的需要添加 ？对于的值
		statementHandler.parameterize(statement);
		return statement;
	}

}
